package care.www.skinrun.com.opencvexam;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import org.opencv.android.OpenCVLoader;
import org.opencv.android.Utils;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Size;
import org.opencv.imgproc.Imgproc;

import java.io.InputStream;

/**
 * http://blog.csdn.net/jia20003/article/details/53126321
 */

public class MainActivity extends AppCompatActivity {

    private double max_size = 1024;
    private int PICK_IMAGE_REQUEST = 1;
    private ImageView myImageView;
    private Bitmap selectbp;




    // Used to load the 'native-lib' library on application startup.
    static {
        System.loadLibrary("native-lib");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        staticLoadCVLibraries();

        myImageView = (ImageView)findViewById(R.id.img);
        myImageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
        Button selectImageBtn = (Button)findViewById(R.id.selecte_img);
        selectImageBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // makeText(MainActivity.this.getApplicationContext(), "start to browser image", Toast.LENGTH_SHORT).show();
                selectImage();
            }
        });

        Button processBtn = (Button)findViewById(R.id.handler_img);
        processBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // makeText(MainActivity.this.getApplicationContext(), "hello, image process", Toast.LENGTH_SHORT).show();
//                convertGray();
                //convertBlur();
                filter2D();
            }
        });

    }

    //OpenCV库静态加载并初始化
    private void staticLoadCVLibraries(){
//        boolean load = OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_11, this, new BaseLoaderCallback(this) {
//            @Override
//            public void onManagerConnected(int status) {
//                super.onManagerConnected(status);
//                switch (status){
//                    case BaseLoaderCallback.SUCCESS:
//                        Log.i("CV", "Open CV Libraries loaded...");
//                        break;
//                }
//            }
//        });
//        if(load) {
//            Log.i("CV", "Open CV Libraries loaded...");
//        }

        boolean load = OpenCVLoader.initDebug();
    }

    private void convertGray() {
        Mat src = new Mat();
        Mat temp = new Mat();
        Mat dst = new Mat();
        Utils.bitmapToMat(selectbp, src);
        Imgproc.cvtColor(src, temp, Imgproc.COLOR_BGRA2BGR);
        Log.i("CV", "image type:" + (temp.type() == CvType.CV_8UC3));
        Imgproc.cvtColor(temp, dst, Imgproc.COLOR_BGR2GRAY);
        Utils.matToBitmap(dst, selectbp);
        myImageView.setImageBitmap(selectbp);
    }

    private void filter2D(){
        Mat srcMat = new Mat(selectbp.getHeight(),selectbp.getWidth(),CvType.CV_8UC4);
        Utils.bitmapToMat(selectbp, srcMat);
        Mat dst = new Mat();
        Mat kernel = new Mat(3,3,CvType.CV_16SC1);
        kernel.put(0, 0, 0, -1, 0, -1, 5, -1, 0, -1, 0);
        Imgproc.filter2D(srcMat,srcMat,srcMat.depth(),kernel);
        Utils.matToBitmap(srcMat, selectbp);
        myImageView.setImageBitmap(selectbp);
    }

    private void convertBlur(){
//        Mat src = new Mat();//new Mat(selectbp.getHeight(),selectbp.getWidth(),CvType.CV_8UC4);
//        Utils.bitmapToMat( selectbp,src);
//        Imgproc.cvtColor(src, src, Imgproc.COLOR_BGR2GRAY);
//        Imgproc.GaussianBlur(src,src,new Size(3,3),0);
//        Imgproc.adaptiveThreshold(src, src, 255, Imgproc.ADAPTIVE_THRESH_MEAN_C, Imgproc.THRESH_BINARY_INV, 5, 4);
        myImageView.setImageBitmap(sobel(selectbp));
    }

    public Bitmap sobel(Bitmap srcBitmap) {
        Mat srcMat = new Mat();
        Mat dstMat = new Mat();
        //显示progressbar
        //  mProgressBar.setVisibility(ProgressBar.VISIBLE);
        int ddepth = -1;
        // 降噪
        Utils.bitmapToMat(srcBitmap, srcMat);
        //Imgproc.GaussianBlur(srcMat, srcMat, new Size(3, 3), 0, 0,Imgproc.BORDER_DEFAULT);
        Imgproc.GaussianBlur(srcMat,srcMat,new Size(3,3),0);
        Utils.matToBitmap(srcMat, srcBitmap);
        // 灰化
        Bitmap grayBitmap = gray(srcBitmap);
        Mat gray_x = new Mat();
        Mat gray_y = new Mat();
        Mat gray_x_y = new Mat();
        Utils.bitmapToMat(grayBitmap, srcMat);// srcMat is gray now
        // x轴求导
        Imgproc.Sobel(srcMat, gray_x, ddepth, 1, 0);
        // y轴求导
        Imgproc.Sobel(srcMat, gray_y, ddepth, 0, 1);

        Core.addWeighted(gray_x, 0.5, gray_y, 0.5, 0.0, gray_x_y);
        Bitmap dstBitmap = Bitmap.createBitmap(srcBitmap.getWidth(),
                srcBitmap.getHeight(), Bitmap.Config.RGB_565);
        Utils.matToBitmap(gray_x_y, dstBitmap);
        return srcBitmap;
    }

    public Bitmap gray(Bitmap srcBitmap) {
        Mat srcMat = new Mat();
        Mat dstMat = new Mat();
        Utils.bitmapToMat(srcBitmap, srcMat);
        Bitmap dstBitmap = Bitmap.createBitmap(srcBitmap.getWidth(),
                srcBitmap.getHeight(), Bitmap.Config.RGB_565);
        Imgproc.cvtColor(srcMat, dstMat, Imgproc.COLOR_RGB2GRAY);
        Utils.matToBitmap(dstMat, dstBitmap);
        return dstBitmap;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
            Uri uri = data.getData();
            try {
                Log.d("image-tag", "start to decode selected image now...");
                InputStream input = getContentResolver().openInputStream(uri);
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = true;
                BitmapFactory.decodeStream(input, null, options);
                int raw_width = options.outWidth;
                int raw_height = options.outHeight;
                int max = Math.max(raw_width, raw_height);
                int newWidth = raw_width;
                int newHeight = raw_height;
                int inSampleSize = 1;
                if(max > max_size) {
                    newWidth = raw_width / 2;
                    newHeight = raw_height / 2;
                    while((newWidth/inSampleSize) > max_size || (newHeight/inSampleSize) > max_size) {
                        inSampleSize *=2;
                    }
                }

                options.inSampleSize = inSampleSize;
                options.inJustDecodeBounds = false;
                options.inPreferredConfig = Bitmap.Config.ARGB_8888;
                selectbp = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri), null, options);

                myImageView.setImageBitmap(selectbp);

                if(input!=null) {
                    input.close();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void selectImage() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent,"选择图像..."), PICK_IMAGE_REQUEST);
    }


}
